<template>
  <ChartContainer :title="title">
    <div class="chart" ref="chartRef"></div>
  </ChartContainer>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted, toRefs } from 'vue';
import * as echarts from 'echarts';
import ChartContainer from './ChartContainer.vue';
import { getHTotalUsers } from '../../api/auth';

// 定义数据类型
interface AgeDistributionItem {
  name: string;
  value: number;
  count: number;
}

defineOptions({
  name: 'RightBottom'
});

const props = defineProps({
  title: {
    type: String,
    default: '用户年龄分布'
  },
  chartData: {
    type: Array,
    default: () => []
  }
});

const { title } = toRefs(props);

const chartRef = ref(null);
let chart: echarts.ECharts | null = null;
const ageData = ref<AgeDistributionItem[]>([]);

const fetchAgeData = async () => {
  try {
    const res = await getHTotalUsers();
    if (res.data && res.data.code === 200) {
      if (res.data.ageDistribution && Array.isArray(res.data.ageDistribution)) {
        ageData.value = res.data.ageDistribution.map((item: any) => ({
          name: item.ageRange || '未知年龄',
          value: item.percentage || 0,
          count: item.count || 0
        }));
      }
      initChart();
    }
  } catch (error) {
    console.error('获取用户年龄分布数据失败:', error);
    initChart();
  }
};

const initChart = () => {
  if (!chartRef.value) return;
  
  chart = echarts.init(chartRef.value);
  
  if (ageData.value.length === 0) {
    chart.setOption({
      title: {
        text: '暂无年龄分布数据',
        left: 'center',
        top: 'middle',
        textStyle: {
          color: '#fff',
          fontSize: 16
        }
      }
    });
    return;
  }
  
  const option = {
    color: ['#4b86db', '#6ac0e7', '#ef7a6d', '#f2a85f', '#7fc37e'],
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'middle',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: '#fff',
        fontSize: 10
      },
      formatter: function(name: string) {
        const item = ageData.value.find(item => item.name === name);
        return `${name}: ${item ? item.value : 0}%`;
      }
    },
    series: [
      {
        name: '年龄分布',
        type: 'pie',
        radius: ['40%', '65%'],
        center: ['35%', '50%'],
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 12,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: ageData.value
      }
    ]
  };
  
  chart.setOption(option);
};

watch(() => props.chartData, () => {
  if (props.chartData && Array.isArray(props.chartData) && props.chartData.length > 0) {
    ageData.value = props.chartData.map((item: any) => ({
      name: item.name || '未知',
      value: item.value || 0,
      count: item.count || 0
    }));
    if (chart) {
      chart.dispose();
      initChart();
    }
  }
}, { deep: true });

onMounted(() => {
  fetchAgeData().catch(error => {
    console.error('获取用户年龄分布数据失败:', error);
    if (chart) {
      chart.dispose();
    }
    initChart();
  });
  
});

onUnmounted(() => {
  if (chart) {
    chart.dispose();
  }
});

// 添加refresh方法供父组件调用
const refresh = async () => {
  await fetchAgeData();
};

// 暴露refresh方法
defineExpose({
  refresh
});
</script> 